package com.dh.leetcode.zero;

import org.junit.Assert;
import org.junit.Test;

/**
 * @ClassName: _48_rotate_image
 * @Description: 48. 旋转图像
 * 给定一个 n × n 的二维矩阵表示一个图像。
 * <p>
 * 将图像顺时针旋转 90 度。
 * <p>
 * 说明：
 * <p>
 * 你必须在原地旋转图像，这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。
 * <p>
 * 示例 1:
 * <p>
 * 给定 matrix =
 * [
 * [1,2,3],
 * [4,5,6],
 * [7,8,9]
 * ],
 * <p>
 * 原地旋转输入矩阵，使其变为:
 * [
 * [7,4,1],
 * [8,5,2],
 * [9,6,3]
 * ]
 * 示例 2:
 * <p>
 * 给定 matrix =
 * [
 * [ 5, 1, 9,11],
 * [ 2, 4, 8,10],
 * [13, 3, 6, 7],
 * [15,14,12,16]
 * ],
 * <p>
 * 原地旋转输入矩阵，使其变为:
 * [
 * [15,13, 2, 5],
 * [14, 3, 4, 1],
 * [12, 6, 8, 9],
 * [16, 7,10,11]
 * ]
 * <p>
 * <p>
 * https://leetcode-cn.com/problems/rotate-image/
 * @Author: shouzimu
 * @Date: 2020/12/19 9:18
 */
public class _48_rotate_image {
    /**
     * 由外向内一圈一圈旋转
     * 先旋转角，再依次向内旋转，每次4个
     * <p>
     * 假设 当前坐标为（i,j) 矩阵 n*n
     * 则（i,j) = (n-j-1,i)
     * 为了防止值被覆盖，每次需要处理4个下标
     *
     * @param matrix
     */
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        int y = 0;
        int quan = Math.max(1, n / 2);
        for (int i = 0; i < quan; i++) {
            for (int j = y; j < n - y - 1; j++) {
                int ax = i, ay = j;
                int bx = n - ay - 1, by = ax;
                int cx = n - by - 1, cy = bx;
                int dx = n - cy - 1, dy = cx;
                int tmp = matrix[ax][ay];
                matrix[ax][ay] = matrix[bx][by];
                matrix[bx][by] = matrix[cx][cy];
                matrix[cx][cy] = matrix[dx][dy];
                matrix[dx][dy] = tmp;
            }
            y++;
        }
    }

    public void rotate_wrong(int[][] matrix) {
        int n = matrix.length;
        int[][] array2 = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                array2[i][j] = matrix[n - j - 1][i];
            }
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                matrix[i][j] = array2[i][j];
            }
        }
    }

    @Test
    public void rotateTest() {
        int[][] array = new int[][]{
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
        };
        rotate(array);
        Assert.assertArrayEquals(new int[][]{
                {7, 4, 1},
                {8, 5, 2},
                {9, 6, 3}
        }, array);

        array = new int[][]{
                {5, 1, 9, 11},
                {2, 4, 8, 10},
                {13, 3, 6, 7},
                {15, 14, 12, 16}
        };
        rotate(array);
        Assert.assertArrayEquals(new int[][]{
                {15, 13, 2, 5},
                {14, 3, 4, 1},
                {12, 6, 8, 9},
                {16, 7, 10, 11}
        }, array);
    }

}
